<?php
namespace app\common\process;

class OrderRefundIpl extends Info {
    protected $model = 'jy\\OrderRefund';
    protected $only = null;

    //获取only
    public function getOnly() {
        if($this->only == null) {
            $this->only = loadOnly('jy\\OrderRefund');
        }
        return $this->only;
    }

    //申请退款实际执行
    public function refund_ipl($post) {
    	$model = $this->model;
    	$fee = $this->get_refund_money($post);
    	$orid = $this->save_refund($post['oid'], $post['uid'], $fee);

    	$this->save_order_refund_log_ipl($orid, 'yonghucaozuo', $post['uid'], '申请退款', $post['remark'], $post['iids']);
    	$this->save_order_refund_products_ipl($orid, $post['opids'], $post['nums']);

    }

    //保存退款记录
    public function save_refund($oid, $uid, $fee) {
        $model = $this->model;
    	$statusEnum = loadEnum('OrderRefundStatus');
    	$refund_out_trade_no = loadTool('Number')->refund_out_trade_no();
        $model->id = null;
    	$model->isUpdate(false)->save([
            'uid'                 => $uid,
    		'oid'                 => $oid,
    		'refund_out_trade_no' => $refund_out_trade_no,
    		'fee'                 => $fee,
    		'status'              => $statusEnum->code2key('senqingtuikuang')
    	]);
    	return $model->id;
    }

    //保存操作记录
    public function save_order_refund_log_ipl($orid, $type, $relatedid, $name, $remark = '', $iids = '', $express_number = '') {
    	$only = loadOnly('jy\\OrderRefund');
    	$typeEnum = loadEnum('OrderRefundLogType');
    	$type = $typeEnum->code2key($type);
        $orderRefundLogModel = $only->getModel('jy\\OrderRefundLog');
        $orderRefundLogModel->id = null;
    	$orderRefundLogModel->isUpdate(false)->save([
    		'orid'           => $orid,
    		'type'           => $type,
    		'relatedid'      => $relatedid,
    		'name'           => $name,
    		'remark'         => $remark,
            'express_number' => $express_number
    	]);
        $orlid = $orderRefundLogModel->id;
        if($iids) {
            $datas = [];
            foreach($iids as $k => $iid) {
                $datas[] = [
                    'orlid' => $orlid,
                    'iid'   => $iid
                ];
            }
            $only->getModel('jy\\OrderRefundLogImageNexus')->isUpdate(false)->saveAll($datas);
        }
    	return $orlid;
    }

    //保存所有的退款产品
    public function save_order_refund_products_ipl($orid, $opids, $nums) {
    	foreach($opids as $k => $opid) {
    		$this->save_order_refund_product_ipl($orid, $opid, $nums[$k]);
    	}
    }

    //保存退款产品
    public function save_order_refund_product_ipl($orid, $opid, $num) {
    	$only = loadOnly('jy\\OrderRefund');
        $model = $only->getModel('jy\\OrderRefundProduct');
        $model->id = null;
    	$model->isUpdate(false)->save([
    		'orid' => $orid,
    		'opid' => $opid,
    		'num'  => $num
    	]);
    	return $this;
    }

    //根据参数获取退款金额
    public function get_refund_money($post) {
    	$only = loadOnly('jy\\SnapshotProductSpecs');
    	$opids = $post['opids'];
        $nums = $post['nums'];

        $fee = 0;

        foreach ($opids as $key => $opid) {
        	$num = $nums[$key];
        	$orderProduct = $only->find('jy\\OrderProduct', $opid);
            $snapshotProductSpecs = $only->find4orderProduct($orderProduct['snapshotid'], $orderProduct['psid']);
        	$fee += $snapshotProductSpecs['price'] * $num;
        }
        return $fee;
    }

    //获取退款单信息
    public function info_ipl($id) {
        $only = $this->getOnly();
        return $only->find('jy\\OrderRefund', $id);        
    }

    //获取退款单详情
    public function info_all_ipl($id) {
        $row = $this->info_ipl($id);
        $row->append($this->append);
        $row->append('express_number');
        return $row;
    }

    //退款申请状态修改
    public function set_status_ipl($id, $statusCode) {
        $statusEnum = loadEnum('OrderRefundStatus');
        $model = $this->model;
        $row = $model->find($id);
        $row->status = $statusEnum->code2key($statusCode);
        $row->save();
        return $row->id;
    }

    //店铺同意退款
    public function store_refund_handle_agree_ipl($post) {
        if(loadOnly('jy\\OrderProduct')->isReturnProducts4refund($post['id'])) {
            $this->store_refund_handle_buyer_returns_ipl($post);
        } else {
            $this->store_refund_handle_refund_ipl($post);
        }
    }

    //店铺同意退款后等待买家退货
    public function store_refund_handle_buyer_returns_ipl($post) {
        $this->set_status_ipl($post['id'], 'dengdaimaijiatuihuo');
        $this->save_order_refund_log_ipl($post['id'], 'shangjiacaozuo', $post['sid'], '商家同意了退款申请', $post['remark'], $post['iids']);
    }

    //店铺同意退款后直接退款
    public function store_refund_handle_refund_ipl($post) {
        $this->set_status_ipl($post['id'], 'tuikuangchenggong');
        $this->save_order_refund_log_ipl($post['id'], 'shangjiacaozuo', $post['sid'], '商家同意了退款申请', $post['remark'], $post['iids']);
        $this->send_refund_ipl($post['id']);
    }


    //店铺拒绝退款
    public function store_refund_handle_refuse_ipl($post) {
        $this->set_status_ipl($post['id'], 'maijiajujuetuikuan');
        $this->save_order_refund_log_ipl($post['id'], 'shangjiacaozuo', $post['sid'], '商家拒绝了退款申请', $post['remark'], $post['iids']);
    }

    //买家退货
    public function user_return_product_ipl($post) {
        $this->set_status_ipl($post['id'], 'tuihuozhong');
        $this->save_order_refund_log_ipl($post['id'], 'yonghucaozuo', $post['uid'], '买家已经将退货商品发出', $post['remark'], $post['iids'], $post['expressNumber']);
        $this->save_express_number($post['id'], $post['expressNumber']);
    }

    //保存退货订单
    public function save_express_number($orid, $express_number) {
        $only = $this->getOnly();
        $model = $only->getModel('jy\\OrderRefundExpressNumber');
        $model->id = null;
        $model->save([
            'orid'           => $orid,
            'express_number' => $express_number
        ]);
        return $model->id;
    }

    //商家收到退货
    public function store_received_return_ipl($post) {
        $this->set_status_ipl($post['id'], 'maijiayiqianshou');
        $this->save_order_refund_log_ipl($post['id'], 'shangjiacaozuo', $post['sid'], '卖家已经收到退货', $post['remark'], $post['iids']);
    }

    //商家收到退货后同意退款
    public function store_refund_product_handle_agree_ipl($post) {
        $this->set_status_ipl($post['id'], 'tuikuangchenggong');
        $this->save_order_refund_log_ipl($post['id'], 'shangjiacaozuo', $post['sid'], '商家收到产品后同意了退款申请', $post['remark'], $post['iids']);
        $this->send_refund_ipl($post['id']);
    }

    //商家收到退货后拒绝退款
    public function store_refund_product_handle_refuse_ipl($post) {
        $this->set_status_ipl($post['id'], 'tuihuomaijiajujue');
        $this->save_order_refund_log_ipl($post['id'], 'shangjiacaozuo', $post['sid'], '商家收到产品后拒绝了退款申请', $post['remark'], $post['iids']);
    }

    //申请管理员介入
    public function apply_for_administrator_intervention_ipl($post) {
        $this->set_status_ipl($post['id'], 'shenqingguanliyuanjieru');
        $this->save_order_refund_log_ipl($post['id'], 'yonghucaozuo', $post['uid'], '用户申请管理员介入', $post['remark'], $post['iids']);
    }

    //管理员同意退款
    public function administrator_hanlde_agree_ipl($post) {
        $this->save_order_refund_log_ipl($post['id'], 'guanliyuancaozuo', $post['aid'], '管理员同意退款申请', $post['remark'], $post['iids']);
        if(loadOnly('jy\\OrderProduct')->isReturnProducts4refund($post['id'])) {
            $this->administrator_refund_handle_buyer_returns_ipl($post);
        } else {
            $this->administrator_refund_handle_refund_ipl($post);
        }
        
    }

    //管理员同意退款后退货退款
    public function administrator_refund_handle_buyer_returns_ipl($post) {
        $this->set_status_ipl($post['id'], 'dengdaimaijiatuihuo2');
    }

    //管理员同意退款后直接退款
    public function administrator_refund_handle_refund_ipl($post) {
        $this->set_status_ipl($post['id'], 'tuikuangchenggong');
        $this->send_refund_ipl($post['id']);
    }

    //管理员拒绝退款
    public function administrator_hanlde_refuse_ipl($post) {
        $this->set_status_ipl($post['id'], 'guanliyuanjujuetuikuan');
        $this->save_order_refund_log_ipl($post['id'], 'guanliyuancaozuo', $post['aid'], '管理员拒绝退款申请', $post['remark'], $post['iids']);
    }

    //管理员同意退款后买家退货
    public function user_return_product2_ipl($post) {
        $this->set_status_ipl($post['id'], 'tuihuozhong2');
        $this->save_order_refund_log_ipl($post['id'], 'yonghucaozuo', $post['uid'], '买家已经将退货商品发出', $post['remark'], $post['iids'], $post['expressNumber']);
        $this->save_express_number($post['id'], $post['expressNumber']);
    }

    //管理员同意退款后商家收到退货
    public function store_received_return2_ipl($post) {
        $this->set_status_ipl($post['id'], 'maijiayiqianshou2');
        $this->save_order_refund_log_ipl($post['id'], 'shangjiacaozuo', $post['sid'], '卖家已经收到退货', $post['remark'], $post['iids']);
    }

    //管理员同意退款后商家收到退货后同意退款
    public function store_refund_product2_handle_agree_ipl($post) {
        $this->set_status_ipl($post['id'], 'tuikuangchenggong');
        $this->save_order_refund_log_ipl($post['id'], 'shangjiacaozuo', $post['sid'], '商家收到产品后同意了退款申请', $post['remark'], $post['iids']);
        $this->send_refund_ipl($post['id']);
    }

    //管理员同意退款后商家收到退货后拒绝退款
    public function store_refund_product2_handle_refuse_ipl($post) {
        $this->set_status_ipl($post['id'], 'tuihuomaijiajujue2');
        $this->save_order_refund_log_ipl($post['id'], 'shangjiacaozuo', $post['sid'], '商家收到产品后拒绝了退款申请', $post['remark'], $post['iids']);
    }

    //再次申请管理员介入
    public function apply_for_administrator_intervention2_ipl($post) {
        $this->set_status_ipl($post['id'], 'shenqingguanliyuanjieru2');
        $this->save_order_refund_log_ipl($post['id'], 'yonghucaozuo', $post['uid'], '用户申请管理员介入', $post['remark'], $post['iids']);
    }

    //再次申请管理员介入管理员同意退款
    public function administrator_hanlde2_agree_ipl($post) {
        $this->save_order_refund_log_ipl($post['id'], 'guanliyuancaozuo', $post['aid'], '管理员同意退款申请', $post['remark'], $post['iids']);
        $this->set_status_ipl($post['id'], 'tuikuangchenggong');
        $this->send_refund_ipl($post['id']);
        
    }

    //管理员拒绝退款
    public function administrator_hanlde2_refuse_ipl($post) {
        $this->set_status_ipl($post['id'], 'guanliyuanjujuetuikuan2');
        $this->save_order_refund_log_ipl($post['id'], 'guanliyuancaozuo', $post['aid'], '管理员拒绝退款申请', $post['remark'], $post['iids']);
    }

    //发送退款请求完成退款
    public function send_refund_ipl($id) {
        $refund = loadOnly('jy\\OrderRefund')->find('jy\\OrderRefund', $id);
        $order = loadOnly('jy\\Order')->find('jy\\Order', $refund['oid']);
        $model = loadModel('tyyh\\UserWallet');
        $orderModel = loadModel('jy\\Order');

        try {
            $model->startTrans();
            $orderModel->startTrans();
            $app = loadTool('Wechat')->payment($order['route']);

            if($order['balance'] && $order['refund_fee'] <= $order['balance']) {
                $refundBalance = $order['balance'] - $order['refund_fee'];

                loadProcess('UserWallet')->set_balance_ipl($order['uid'], $refundBalance);
            } else {
                $refundBalance = 0;
            }

            if($refund['fee'] > $refundBalance && $refundBalance > 0) {
                $result = $app->refund->byTransactionId($order['transaction_id'], $refund['refund_out_trade_no'], $order['total_fee'] * 100, ($refund['fee'] - $refundBalance) * 100);
                $validate = loadValidate('wechat\\EasyWchatResult');
                if(!$validate->check($result)) {
                    throw new \Exception($validate->getError());
                }
            }

            $order->refund_fee = $order->refund_fee + $refund['fee'];
            $order->save();
            //refund_fee 退款金额
            $model->commit();
            $orderModel->commit();
        } catch(\Exception $e) {
            $model->rollback();
            $orderModel->rollback();
            throw $e;
        }
    }
}
